package com.reeygu.item.exception;

import com.reeygu.item.vo.RespBean;
import com.reeygu.item.vo.RespBeanEnum;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 异常处理类
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 异常处理
     * @param e 异常数据
     * @return
     */
    @ExceptionHandler
    public RespBean exceptionHandler(Exception e){
        //异常属于全局异常
        if(e instanceof GlobalException) {
            GlobalException ge = (GlobalException) e;
            return RespBean.error(ge.getRespBeanEnum());
        }
        //异常属于validation注解功能中的参数绑定异常
        if(e instanceof BindException) {
            BindException be = (BindException) e;
            RespBean respBean = RespBean.error(RespBeanEnum.ERROR);
            //修改msg为注解定义的消息
            respBean.setMessage(be.getBindingResult().getAllErrors().get(0).getDefaultMessage());
            return respBean;
        }
        //其他异常抛出默认值
        return RespBean.error(RespBeanEnum.ERROR);
    }
}
